{include file="$header" /}
<div class="mk-app-warp">
    <mk-table-header
        keyword-title="内容描述关键词搜索"
        :add-url="addUrl"
        :del-url="delUrl"
        :rows="rows"
        @del="del()"
        @add="openDrawer()"
        @search="searchData($event)">
        <template v-slot:button>
            <el-button 
                v-if="synchroAuthority && language !== langDefault"
                size="small" 
                icon="el-icon-warning-outline"
                type="warning" 
                @click="synchro()">
                <span class="title">同步</span>
            </el-button>
        </template>
    </mk-table-header>
    <el-table
        class="sort-table"
        row-key="id"
        ref="dragTable" 
        highlight-current-row
        :data="table"
        v-loading="loading"
        @selection-change="checkSelected">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="cover" label="文件">
            <template slot-scope="scope">
                <el-image :src="domain + scope.row.cover" class="mk-table-cover">
                    <div slot="error" class="image-slot">
                        <img class="error-image" :src="static + '/images/error.png'"/>
                    </div>
                </el-image>
            </template>
        </el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="status" label="状态" width="100px">
            <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="fieldEdit(scope.row, 'status')"
                    :disabled="editAuthority === false">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
            <template slot-scope="scope">
                <mk-table-public
                    :edit-url="editUrl"
                    :del-url="delUrl"
                    @edit="openDrawer(scope.row)"
                    @del="del(scope.row)">
                </mk-table-public>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageChange"
        :current-page="search.page"
        :page-size="search.pageSize"
        :page-sizes="pageSizes"
        :total="pageTotal"
        layout="total, sizes, prev, pager, next, jumper"
        background
        hide-on-single-page>
    </el-pagination>
</div>
{include file="banner/drawer" /}
{include file="$component" /}
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                rows: [],
                table: [],
                catalog: tree.convertString({:json_encode($catalog)}),
                search:{
                    date: [],
                    keyword: "",
                    page: 1,
                    pageSize: 14,
                },
                pageSizes: [14, 50, 100, 200, 500, 1000, 3000],
                pageTotal: 0,
                url: "banner/index",
                addUrl: "banner/save",
                delUrl: "banner/delete",
                editUrl: "banner/update",
                synchroUrl: "banner/synchro",
                sortUrl: "banner/sort",
                loading: false,
                drawer: false,
                drawerData: {},
                drawerForm: {
                    catalog_id: [],
                    title: "",
                    detail: "",
                    cover: "",
                    video: "",
                    content: "",
                    link: "",
                    status: 1,
                },
                drawerRules: {
                    catalog_id: [
                        { required: true, message: '请选择所属组别', trigger: 'blur' },
                    ],
                    cover: [
                        { required: true, message: '上传banner图', trigger: 'blur' },
                    ],
                },
                drawerLoading: false,
            }
        },
        mounted () {
            this.setSort();
        },
        created () {
            this.getData();
        },
        computed: {
            editAuthority() {
                return authorityPath.indexOf(this.editUrl) !== -1;
            },
            synchroAuthority() {
                return authorityPath.indexOf(this.synchroUrl) !== -1
            },
            sortAuthority() {
                return authorityPath.indexOf(this.sortUrl) !== -1;
            },
        },
        methods: {
            /**
             * 获取数据
             */
            getData() {
                let self     = this;
                request.post(self.url, self.search, function(res) {
                    self.table     = res.data;
                    self.pageTotal = res.count;
                });
            },
            /**
             * 打开抽屉
             * @param  {Object} row 当前行
             */
            openDrawer(row = "") {
                let self = this;
                self.drawerData = row === "" ? JSON.parse(JSON.stringify(self.drawerForm)) : JSON.parse(JSON.stringify(row));
                self.drawer = true;
            },
            /**
             * 保存内容
             */
            saveDrawer() {
                let self = this;
                self.$refs.drawerData.validate((valid) => {
                    if (valid) {
                        let requestUrl = typeof self.drawerData.id === 'undefined' ? self.addUrl : self.editUrl;
                        self.drawerLoading = true;
                        request.post(requestUrl, self.drawerData, function(res){
                            self.drawerLoading = false;
                            if (res.status === 'success') {
                                self.getData();
                                self.drawer = false;
                            } else {
                                self.$message({ showClose: true, message: res.message, type: res.status});
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            /**
             * 单字段修改
             * @param  {Object} row 当前行
             */
            fieldEdit(row, field) {
                let self = this;
                request.post(self.editUrl, {id: row.id, value: row[field], field: field}, function(res) {
                    if (res.status != 'success') {
                        self.$message({ showClose: true, message: res.message, type: res.status});
                        self.getData();
                    }
                });
            },
            /**
             * 行删除、批量删除
             * @param  {Object} row 当前行
             */
            del(row = "") {
                let self = this;
                let ids  = row === "" ? common.arrayColumn(self.rows,'id') : [row.id]; 
                self.$confirm('确定删除吗？', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.post(self.delUrl, {'ids': ids}, function(res){
                        if (res.status === 'success') {
                            self.getData();
                        } else {
                            self.$message({ showClose: true, message: res.message, type: res.status});
                        }
                    });
                }).catch(() => {});
            },
            /**
             * 选中行
             * @param  {Object} rows 多行数
             */
            checkSelected(rows) {
                this.rows = rows;
            },
            /**
             * 关键词/日期搜索
             * @param  {Object} value 搜索内容
             */
            searchData(value) {
                this.search = Object.assign({}, this.search, {page: 1, date: value.date, keyword: value.keyword});
            },
            /**
             * 分页个数改变时
             * @param  {Number} val 每页数量
             */
            pageSizeChange(val) {
                this.search = Object.assign({}, this.search, {pageSize: val});
            },
            /**
             * 分页改变时
             * @param  {String} val 当前页
             */
            pageChange(val) {
                this.search = Object.assign({}, this.search, {page: val});
            },
            /**
             * 拖动排序
             */
            setSort(){
                let self = this;
                let el   = self.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
                self.sortable = Sortable.create(el,{
                    animation: 300,
                    forceFallback: true,
                    delay: 20,
                    onEnd: evt => {
                        if (evt.newIndex !== evt.oldIndex) {
                            let targetRow = self.table.splice(evt.oldIndex, 1)[0];
                            self.table.splice(evt.newIndex, 0, targetRow);
                            let sort = typeof self.table[evt.newIndex + 1] === 'undefined' ? 0 : self.table[evt.newIndex + 1]['sort'];
                            request.post(self.sortUrl, {sort: sort, row: self.table[evt.newIndex]}, function(res){
                                self.getData();
                                if (res.status !== 'success') {
                                    self.$message({ showClose: true, message: res.message, type: res.status});
                                }
                            });
                        }
                    }
                })
            },
            /**
             * 同步主语言数据
             * @param  {string} name 需要同步的数据，空代表全部
             */
            synchro() {
                let self = this;
                self.$confirm('同步主语言后，当前语言的数据将不存在，确定同步吗？', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.post(self.synchroUrl, {}, function(res) {
                        self.$message({ showClose: true, message: res.message, type: res.status });
                        self.getData();
                    });
                }).catch(() => {});
            },
        },
        watch: {
            drawer(v) {
                if(! v){
                    this.$refs.drawerData.resetFields();
                }
            },
            search() {
                this.getData();
            }
        }
    })
</script>
{include file="$footer" /}